package com.store.orm.mysql.handler;

import com.store.orm.mysql.MySQLUtil;
import com.store.orm.util.FieldUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 宫静雨
 * @version 1.0
 */
public class ListRSHandler implements ResultSetHandler {
    private MySQLUtil UTIL ;
    private static final Logger logger = LoggerFactory.getLogger(ListRSHandler.class);

    public ListRSHandler(MySQLUtil UTIL) {
        this.UTIL = UTIL;
    }

    @Override
    public List<Map<String, Object>> handler(ResultSet resultSet) {
        try {
            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();
            List<Map<String, Object>> list = new ArrayList<>();
            while (resultSet.next()) {
                Map<String, Object> map = new LinkedHashMap<>();
                for (int i = 0; i < columnCount; i++) {
                    String key = metaData.getColumnLabel(i + 1);
                    Object v = resultSet.getObject(i + 1);
                    if (UTIL.isCamelCase()) {
                        key = FieldUtil.mysqlToPojo(key);
                    }
                    map.put(key, v);
                }
                list.add(map);
            }
            return list;
        } catch (SQLException e) {
            logger.error("处理 ResultSet 时发生错误{}", e.getMessage());
            throw new RuntimeException();
        }
    }

    @Override
    public <T> List<T> handler(ResultSet resultSet, Class<T> cls) {
        try {
            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();
            List<T> list = new ArrayList<>();
            while (resultSet.next()) {
                T res = cls.newInstance();
                for (int i = 0; i < columnCount; i++) {
                    String key = metaData.getColumnLabel(i + 1);
                    Object v = resultSet.getObject(i + 1);
                    if (UTIL.isCamelCase()) {
                        key = FieldUtil.mysqlToPojo(key);
                    }
                    Field field = cls.getDeclaredField(key);
                    field.setAccessible(true);
                    field.set(res, v);
                }
                list.add(res);
            }
            return list;
        } catch (Exception e) {
            logger.error("处理 ResultSet 时发生错误{}", e.getMessage());
            throw new RuntimeException();
        }
    }
}
